/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦，本文采用木兰宽松许可证第2版]
 * 
 * https://zhiqim.org/project/zhiqim_products/gitsolo.htm
 *
 * gitsolo is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.gitsolo.action;

import org.zhiqim.git.Git;
import org.zhiqim.git.GitConstants;
import org.zhiqim.git.GitWalker;
import org.zhiqim.git.objer.objectid.RevBlob;
import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.extend.ValidateAction;
import org.zhiqim.httpd.validate.ones.IsLen;
import org.zhiqim.kernel.util.Streams;
import org.zhiqim.kernel.util.Strings;

/**
 * 查看一个文件内容
 *
 * @version v1.4.1 @author zouzhigang 2018-5-23 新建与整理
 */
public class RepositoryFileAction extends ValidateAction implements GitConstants
{
    @Override
    protected void validate(HttpRequest request)
    {
        request.addValidate(new IsLen("oid", "请选择一个对象", 40, 40));
    }

    @Override
    protected void perform(HttpRequest request) throws Exception
    {
        String oid = request.getParameter("oid");
        Git git = (Git)request.getAttribute(GIT_ATTRIBUTE_REPOSITORY);
        
        RevBlob obj = git.resolve(oid, RevBlob.class);
        if (obj == null)
        {
            request.returnHistory("请选择一个有效的对象");
            return;
        }
        
        obj.parseHeaders(new GitWalker(git));
        byte[] content = obj.getContent();
        String encoding = Streams.getStreamEncoding(content, content.length);
        
        request.setAttribute("content", Strings.newString(content, encoding));
    }

}
